from importlib.metadata import files
from flask import Flask, request, jsonify
from flask.views import MethodView
import pymysql
from sqlalchemy.testing.suite.test_reflection import users
import os
import datetime
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

#还没解决跨网登录
from flask_cors import CORS
app = Flask(__name__)

# 允许所有来源的请求
CORS(app, resources={r"/*": {"origins": "*"}})

userID = None
ADDID = None




@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有来源的跨域请求
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
    return response


class RegisterAPI(MethodView):
    def post(self):
        # 从请求中获取 JSON 数据
        data = request.get_json()
        password = data.get('password')
        id = data.get('id')

        # 连接到 MySQL 数据库
        try:
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 检查用户名是否已存在
                sql = "SELECT * FROM user WHERE id=%s"
                cursor.execute(sql, (id))
                result = cursor.fetchone()

                if result:
                    # 如果用户已存在，返回状态 0
                    return jsonify({'status': 0}), 200
                else:
                    # 如果用户不存在，将新用户插入数据库
                    sql = "INSERT INTO user (id,password) VALUES (%s,%s)"
                    cursor.execute(sql, (id, password))
                    connection.commit()
                    # 返回状态 1 表示注册成功
                    return jsonify({'status': 1}), 201
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()

        # 如果用户名或密码缺失，返回错误
        return jsonify({'error': 'Invalid data'}), 400


class LoginAPI(MethodView):
    def post(self):
        # 从请求中获取 JSON 数据
        data = request.get_json()
        id = data.get('id')
        global userID
        userID = id  # 保存登录状态
        password = data.get('password')

        # 连接到 MySQL 数据库
        try:
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 检查用户名和密码是否匹配
                sql = "SELECT * FROM user WHERE id=%s AND password=%s"
                cursor.execute(sql, (id, password))
                result = cursor.fetchone()

                if result:
                    print("登上去惹")
                    # 如果凭据正确，返回状态 1 表示登录成功
                    return jsonify({'status': 1}), 200
                else:
                    print("登不上诶")
                    # 如果凭据不正确，返回状态 0 表示登录失败
                    return jsonify({'status': 0}), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()


class AddToCartAPI(MethodView):
    def post(self):
        # 从请求中获取 JSON 数据
        data = request.get_json()
        userid = userID
        productid = data.get('Pro_id')
        quantity = int(data.get('num'))
        typeid = data.get('detail_id')

        # 连接到 MySQL 数据库
        try:
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 检查是否已经存在该用户和商品的记录
                sql_check = "SELECT * FROM cart WHERE userid=%s AND typeid=%s"
                cursor.execute(sql_check, (userid, typeid))
                result = cursor.fetchone()

                if result:
                    # 更新数量
                    new_quantity = int(result['quantity']) + quantity
                    sql_update = "UPDATE cart SET quantity=%s WHERE typeid=%s AND typeid=%s"
                    cursor.execute(sql_update, (new_quantity, typeid, typeid))
                else:
                    # 插入新记录
                    sql_insert = "INSERT INTO cart (userid, typeid, quantity) VALUES (%s, %s, %s)"
                    cursor.execute(sql_insert, (userid, typeid, quantity))

                connection.commit()
                print("加进去惹")
                return jsonify({'status': 1, 'message': '加进去惹'}), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'status': 0, 'error': '数据库出问题惹'}), 500
        finally:
            connection.close()

        # 如果缺少必要的参数，返回错误
        return jsonify({'status': 0, 'error': 'Invalid data'}), 400


class AddCartAPI(MethodView):
    def post(self):
        # 从请求中获取 JSON 数据
        data = request.get_json()
        userid = userID
        typeid = data.get('id')

        # 连接到 MySQL 数据库
        try:
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 检查是否已经存在该用户和商品的记录
                sql_check = "SELECT * FROM cart WHERE userid=%s AND typeid=%s"
                cursor.execute(sql_check, (userid, typeid))
                result = cursor.fetchone()

                if result:
                    # 更新数量
                    new_quantity = int(result['quantity']) + 1
                    sql_update = "UPDATE cart SET quantity=%s WHERE typeid=%s AND typeid=%s"
                    cursor.execute(sql_update, (new_quantity, typeid, typeid))
                else:
                    # 插入新记录
                    sql_insert = "INSERT INTO cart (userid, typeid, quantity) VALUES (%s, %s, %s)"
                    cursor.execute(sql_insert, (userid, typeid, 1))

                connection.commit()
                print("加进去惹")
                return jsonify({'status': 1, 'message': '加进去惹'}), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'status': 0, 'error': '数据库出问题惹'}), 500
        finally:
            connection.close()

        # 如果缺少必要的参数，返回错误
        return jsonify({'status': 0, 'error': 'Invalid data'}), 400


class ProductDetailsAPI(MethodView):
    def get(self):
        # 从请求中获取查询参数
        pro_id = request.args.get('Pro_id')
        print(pro_id)
        # 连接到 MySQL 数据库
        try:
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 查询类型详细信息
                sql_product = "SELECT * FROM type WHERE typeID =%s"
                cursor.execute(sql_product, (pro_id,))
                type_info = cursor.fetchone()

                if not type_info:
                    print("找不到11产品信息")
                    return jsonify({'error': '找不到产品信息'}), 404

                pro = type_info['productID']
                # 查询产品详细信息
                sql_product = "SELECT * FROM product WHERE productID=%s"
                cursor.execute(sql_product, (pro,))
                product_info = cursor.fetchone()

                if not product_info:
                    print("找不到22产品信息")
                    return jsonify({'error': '找不到产品信息'}), 404

                shopID = product_info['owner_id']

                # 查询类型ID列表
                sql_shop = "SELECT * FROM shop WHERE owner_id=%s"
                cursor.execute(sql_shop, (shopID,))
                shop_info = cursor.fetchone()

                # 构造返回结果
                result = {
                    'Pro_name': product_info['name'],
                    'Pro_price': type_info['price'],
                    'Pro_id': product_info['productID'],
                    'store_name': shop_info['name'],
                    'store_id': product_info['owner_id']
                }
                print("查询成功")
                return jsonify(result), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()

        # 如果缺少必要的参数，返回错误
        return jsonify({'error': 'Invalid data'}), 400


class ProductDetailAPI(MethodView):
    def get(self):
        # 从请求中获取查询参数
        pro_id = request.args.get('Pro_id')
        if not pro_id:
            return jsonify({'error': '你也妹给我Pro_id'}), 400

        try:
            # 连接到 MySQL 数据库
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 查询产品详细信息
                sql_product = "SELECT * FROM type WHERE typeID = %s"
                cursor.execute(sql_product, (pro_id,))
                product_info = cursor.fetchone()  # 接下来查product_info里面的productID
                print(product_info)
                if not product_info:
                    print("找不到产品信息")
                    return jsonify({'error': '找不到产品信息'}), 404

                productid = product_info['productID']
                print(productid)
                sql_productA = "SELECT * FROM type WHERE productID = %s"
                cursor.execute(sql_productA, (productid,))
                productA_info = cursor.fetchall()
                print(productA_info)
                # 构造图片路径
                results = []
                for type_item in productA_info:
                    pri_link = type_item['pri_link']
                    src = [
                        f"{pri_link}"
                    ]
                    print(src)
                    # 查询每个 type 的详细信息
                    sql_type_detail = "SELECT * FROM type WHERE typeID = %s AND productID = %s"
                    cursor.execute(sql_type_detail, (pro_id, type_item['productID']))
                    type_detail_info = cursor.fetchone()

                    if not type_detail_info:
                        print(f"找不到类型详细信息: {type_item['typeID']}")
                        continue

                    result = {
                        'Pro_id': type_item['typeID'],
                        'quantity': type_item['quantity'],
                        'Pro_price': type_item['price'],
                        'Pro_detail': type_item['type'],
                        'src': src
                    }
                    results.append(result)

                print("查询成功")
                return jsonify(results), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()


class GetProListView(MethodView):
    def get(self):
        try:
            # 连接到 MySQL 数据库
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 查询 type 表中的数据
                sql_type = "SELECT * FROM type "
                cursor.execute(sql_type)
                types = cursor.fetchall()

                # 构造返回结果
                results = []
                for type_item in types:
                    # 获取 productID
                    product_id = type_item['productID']

                    # 根据 productID 查询 product 表中的 name
                    sql_product = "SELECT name FROM product WHERE productID = %s"
                    cursor.execute(sql_product, (product_id,))
                    product_info = cursor.fetchone()

                    if product_info is None:
                        continue

                    # 构造图片路径
                    pri_link = f"{type_item['pri_link']}"
                    srcs = [f"{pri_link}"]

                    # 构造结果
                    for src in srcs:
                        result = {
                            'src': src,
                            'name': product_info['name'],
                            'price': str(type_item['price']),  # 确保价格为字符串
                            'id': type_item['typeID'],  # 使用 type 表中的 typeID
                            'detail': type_item['type']  # 使用 type 表中的 type 列
                        }
                        results.append(result)

                print("获取商品列表成功")
                return jsonify(results), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()


class DeleteCartItemsView(MethodView):
    def delete(self):
        try:
            # 连接到 MySQL 数据库
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            data = request.json
            type_ids = data.get('type_id', [])

            if not type_ids:
                return jsonify({'error': '缺少 type_id 参数'}), 400

            # 删除选中的商品
            with connection.cursor() as cursor:
                # 删除 cart 表中的记录
                placeholders = ', '.join(['%s'] * len(type_ids))
                sql_delete = f"DELETE FROM cart WHERE typeid IN ({placeholders}) AND userid=%s"
                print(sql_delete)
                print(placeholders)
                cursor.execute(sql_delete, type_ids + [userID])
                connection.commit()

            # 获取删除后的购物车列表
            cart_list = get_cart(connection)

            return jsonify(cart_list), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()


def get_cart(connection):
    try:
        # 连接到 MySQL 数据库
        connection = pymysql.connect(
            host='localhost',  # 数据库地址
            user='root',  # 数据库用户名
            password='root',  # 数据库密码
            db='database',  # 数据库名称
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )
        print("数据库连接成功")
    except Exception as e:
        print(f"草了没连上: {e}")
        return jsonify({'error': '草了没连上'}), 500

    try:
        with connection.cursor() as cursor:
            # 查询所有商品
            sql_products = """
                SELECT 
                    c.typeid, 
                    c.quantity, 
                    t.type, 
                    t.price, 
                    t.pri_link,
                    t.quantity, 
                    s.name AS shop_name 
                FROM cart c 
                INNER JOIN type t ON c.typeid = t.typeid 
                INNER JOIN product p ON p.productID = t.productID
                INNER JOIN shop s ON p.owner_id = s.owner_id 
                WHERE c.userid = %s
            """
            cursor.execute(sql_products, (userID,))
            products = cursor.fetchall()
            print(products)

            # 分组按商家名称
            grouped_products = {}
            for product in products:
                shop_name = product['shop_name']
                if shop_name not in grouped_products:
                    grouped_products[shop_name] = {
                        'shop_name': shop_name,
                        'shop_selected': False,
                        'products': []
                    }
                grouped_products[shop_name]['products'].append({
                    'product_detail': product['type'],
                    'product_price': product['price'],
                    'product_quantity': product['quantity'],
                    'type_id': product['typeid'],
                    'src': f"{product['pri_link']}",
                    'selected': False,
                    'postage': product['quantity']
                })

            # 构建最终的 cart_list
            cart_list = list(grouped_products.values())

            return cart_list
    except Exception as e:
        print(f"数据库出问题惹 : {e}")
        return []


class GetCartView(MethodView):
    def get(self):
        try:
            # 连接到 MySQL 数据库
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")
        except Exception as e:
            print(f"草了没连上: {e}")
            return jsonify({'error': '草了没连上'}), 500

        try:
            with connection.cursor() as cursor:
                # 查询所有商品
                sql_products = """
                    SELECT 
                        c.typeid, 
                        c.quantity, 
                        t.type, 
                        t.price, 
                        t.pri_link,
                        t.quantity, 
                        s.name AS shop_name 
                    FROM cart c 
                    INNER JOIN type t ON c.typeid = t.typeid 
                    INNER JOIN product p ON p.productID = t.productID
                    INNER JOIN shop s ON p.owner_id = s.owner_id 
                    WHERE c.userid = %s
                """
                cursor.execute(sql_products, (userID,))
                products = cursor.fetchall()
                print(products)

                # 分组按商家名称
                grouped_products = {}
                for product in products:
                    shop_name = product['shop_name']
                    if shop_name not in grouped_products:
                        grouped_products[shop_name] = {
                            'shop_name': shop_name,
                            'shop_selected': False,
                            'products': []
                        }
                    grouped_products[shop_name]['products'].append({
                        'product_detail': product['type'],
                        'product_price': product['price'],
                        'product_quantity': product['quantity'],
                        'type_id': product['typeid'],
                        'src': f"{product['pri_link']}",
                        'selected': False,
                        'postage': product['quantity']
                    })

                # 构建最终的 cart_list
                cart_list = list(grouped_products.values())

                return jsonify(cart_list), 200
        except Exception as e:
            print(f"数据库出问题惹 : {e}")
            return jsonify({'error': '数据库出问题惹'}), 500
        finally:
            connection.close()


class LogoutView(MethodView):
    def post(self):
        try:
            # 将全局变量 userID 设置为 null
            global userID
            userID = None
            return jsonify({'message': '退出来惹'}), 200
        except Exception as e:
            print(f"处理登出请求时出错: {e}")
            return jsonify({'error': '处理登出请求时出错'}), 500


class UpdateUserView(MethodView):
    def post(self):
        try:
            # 连接到 MySQL 数据库
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")

            # 获取请求数据
            data = request.json
            username = data.get('username')
            phone = data.get('phone')
            sex = data.get('sex')

            if not username or not phone or not sex:
                return jsonify({'error': '缺少必要的参数'}), 400

            # 更新用户信息
            with connection.cursor() as cursor:
                sql_update = "UPDATE user SET username=%s, phone=%s, sex=%s WHERE id=%s"
                cursor.execute(sql_update, (username, phone, sex, userID))
                connection.commit()

            return jsonify({'message': '修改成功'}), 200
        except Exception as e:
            print(f"处理更新请求时出错: {e}")
            return jsonify({'error': '处理更新请求时出错'}), 500
        finally:
            connection.close()


class GetUserView(MethodView):
    def get(self):
        try:
            # 连接到 MySQL 数据库
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )
            print("数据库连接成功")

            # 查询用户信息
            with connection.cursor() as cursor:
                # 使用反引号包围可能引起关键字冲突的列名
                sql_query = "SELECT  `username`, `phone`, `if_shop`, `sex`, `head` FROM `user` WHERE `id`=%s"
                cursor.execute(sql_query, (userID,))
                user_info = cursor.fetchone()

                if user_info is None:
                    return jsonify({'error': '用户未找到'}), 404

                # 格式化返回的数据
                formatted_user_info = {
                    'id': userID,
                    'username': user_info['username'],
                    'phone': user_info['phone'],
                    'limit': user_info['if_shop'],
                    'sex': user_info['sex'],
                    'head_img': user_info['head']
                }

                print(formatted_user_info)
                return jsonify(formatted_user_info), 200
        except Exception as e:
            print(f"处理查询请求时出错: {e}")
            return jsonify({'error': '处理查询请求时出错'}), 500
        finally:
            connection.close()


from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os

# 配置文件上传目录
UPLOAD_FOLDER = 'C:\\Users\\21270\\Desktop\\qaq\\src\\static\\uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


class UploadAvatarView(MethodView):
    def put(self):
        try:
            # 获取上传的文件
            file = request.files.get('file')

            if file is None:
                return jsonify({'error': '未接收到文件'}), 400

            # 保存文件
            filename = secure_filename(file.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(file_path)

            # 返回文件路径
            file_url = f'/src/static/uploads/{filename}'

            # 更新数据库中的头像路径
            connection = pymysql.connect(
                host='localhost',  # 数据库地址
                user='root',  # 数据库用户名
                password='root',  # 数据库密码
                db='database',  # 数据库名称
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor
            )

            with connection.cursor() as cursor:
                sql_update = "UPDATE user SET head=%s WHERE id=%s"
                cursor.execute(sql_update, (file_url, userID))
                connection.commit()

            return jsonify({'file_path': file_url}), 200
        except Exception as e:
            print(f"处理文件上传时出错: {e}")
            return jsonify({'error': '处理文件上传时出错'}), 500
        finally:
            connection.close()


# 连接到数据库
def get_db_connection():
    connection = pymysql.connect(
        host='localhost',  # 数据库地址
        user='root',  # 数据库用户名
        password='root',  # 数据库密码
        db='database',  # 数据库名称
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    return connection


class ShopView(MethodView):
    def post(self):
        try:
            data = request.json  # 获取JSON数据

            if not data or 'name' not in data or 'description' not in data:
                return jsonify({'error': '缺少必要的参数'}), 400

            # 插入数据到数据库
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 插入数据到shop表
                sql_insert_shop = "INSERT INTO shop (`name`, `describe`, owner_id) VALUES (%s, %s, %s)"
                cursor.execute(sql_insert_shop, (data['name'], data['description'], userID))

                # 更新user表中的limit列
                sql_update_user = "UPDATE user SET if_shop = 1 WHERE id = %s"
                cursor.execute(sql_update_user, (userID,))

                connection.commit()

            return jsonify({'message': '店铺创建成功'}), 201
        except Exception as e:
            print(f"处理店铺创建时出错: {e}")
            return jsonify({'error': '处理店铺创建时出错'}), 500
        finally:
            connection.close()


# 获取当前用户的所有订单
class OrdersView(MethodView):
    def get(self):
        try:
            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 查询当前用户的所有订单
                cursor.execute("SELECT * FROM orders WHERE userid = %s ORDER BY date DESC", (userID,))
                orders = cursor.fetchall()

            orders_data = [
                {
                    'order_id': order['order_id'],
                    'src': order['src'],
                    'date': str(order['date']),
                    'type': order['type'],
                    'shop': order['shop'],
                    'quantity': order['quantity'],
                    'price': float(order['price']),
                    'postage': float(order['postage'])
                }
                for order in orders
            ]

            return jsonify(orders_data), 200
        except Exception as e:
            print(f"处理订单查询时出错: {e}")
            return jsonify({'error': '处理订单查询时出错'}), 500
        finally:
            connection.close()


# 获取所有商家的信息
class StoresView(MethodView):
    def get(self):
        try:
            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 查询所有商家的信息
                cursor.execute("SELECT name FROM shop WHERE owner_id=%s", (userID,))
                stores = cursor.fetchall()
                print(stores)

            stores_data = {
                'name': stores[0].get('name'),
                'id': userID
            }

            return jsonify(stores_data), 200
        except Exception as e:
            print(f"处理商店查询时出错: {e}")
            return jsonify({'error': '处理商店查询时出错'}), 500
        finally:
            connection.close()


# 获取商家的商品列表
class ProductsView(MethodView):
    def post(self):
        try:
            # 获取请求数据
            data = request.json
            store_id = data.get('store_id')

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 查询指定商家的所有商品
                cursor.execute("SELECT * FROM product WHERE owner_id = %s", (userID,))
                products = cursor.fetchall()

            products_data = [
                {
                    'product_id': product['product_id'],
                    'name': product['name'],
                    'price': float(product['price']),
                    'quantity': product['quantity'],
                    'description': product['description']
                }
                for product in products
            ]

            return jsonify(products_data), 200
        except Exception as e:
            print(f"处理商品查询时出错: {e}")
            return jsonify({'error': '处理商品查询时出错'}), 500
        finally:
            connection.close()


import datetime
from datetime import datetime


# 处理购买请求
class BuyView(MethodView):
    def post(self):
        try:
            # 获取请求数据
            data = request.json
            type_ids = data.get('type_id')

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 初始化订单数据
                orders_data = []

                for type_id in type_ids:
                    # 查询 type 表中的数据
                    cursor.execute("SELECT productID FROM type WHERE typeID = %s", (type_id,))
                    type_data = cursor.fetchone()

                    if not type_data:
                        continue

                    product_id = type_data['productID']

                    # 查询 product 表中的数据
                    cursor.execute("SELECT owner_id FROM product WHERE productID = %s", (product_id,))
                    product_data = cursor.fetchone()

                    if not product_data:
                        continue

                    owner_id = product_data['owner_id']

                    # 查询 shop 表中的数据
                    cursor.execute("SELECT name FROM shop WHERE owner_id = %s", (owner_id,))
                    shop_data = cursor.fetchone()

                    if not shop_data:
                        continue

                    shop = shop_data['name']

                    # 查询 cart 表中的数量
                    cursor.execute("SELECT quantity FROM cart WHERE typeID = %s", (type_id,))
                    cart_data = cursor.fetchone()

                    if not cart_data:
                        continue

                    purchase_quantity = cart_data['quantity']

                    # 更新库存
                    if update_inventory(type_id, purchase_quantity) == 0:
                        return jsonify({'error': '库存不足'}), 400
                    # 删除 cart 表中的对应项
                    cursor.execute("DELETE FROM cart WHERE typeID = %s", (type_id,))

                    # 新增订单记录
                    order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}{type_id}"
                    print(order_id)
                    date = datetime.now().date()
                    postage = 10.0  # 邮费为 10.0

                    # 查询 type 表中的 src 和 price
                    cursor.execute("SELECT pri_link, price,type FROM type WHERE typeID = %s", (type_id,))
                    type_info = cursor.fetchone()

                    if not type_info:
                        continue

                    pri_link = type_info['pri_link']
                    price = float(type_info['price']) * purchase_quantity
                    order_type = type_info['type']

                    cursor.execute(
                        "INSERT INTO orders (order_id, userid, src, date, type, shop, quantity, price, postage) "
                        "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                        (order_id, userID, pri_link, date, order_type, shop, purchase_quantity, price, postage)
                    )

                connection.commit()

                return jsonify({'message': '购买成功'}), 200
        except Exception as e:
            print(f"处理购买请求时出错: {e}")
            connection.rollback()
            return jsonify({'error': '处理购买请求时出错'}), 500
        finally:
            connection.close()


# 处理购买请求
class AddOrderView(MethodView):
    def post(self):
        try:
            # 获取请求数据
            data = request.json
            type_id = data.get('detail_id')
            num = int(data.get('num'))  # 确保 num 是整数

            # 更新库存
            if update_inventory(type_id, num) == 0:
                return jsonify({'status': 0, 'message': '库存不足'}), 400

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 查询 type 表中的数据
                cursor.execute("SELECT productID FROM type WHERE typeID = %s", (type_id,))
                type_data = cursor.fetchone()

                if not type_data:
                    return jsonify({'status': 0, 'message': '商品可能已经下架1'}), 200

                product_id = type_data['productID']

                # 查询 product 表中的数据
                cursor.execute("SELECT owner_id FROM product WHERE productID = %s", (product_id,))
                product_data = cursor.fetchone()

                if not product_data:
                    return jsonify({'status': 0, 'message': '商品可能已经下架2'}), 200

                owner_id = product_data['owner_id']

                # 查询 shop 表中的数据
                cursor.execute("SELECT name FROM shop WHERE owner_id = %s", (owner_id,))
                shop_data = cursor.fetchone()

                if not shop_data:
                    return jsonify({'status': 0, 'message': '商品可能已经下架3'}), 200

                shop = shop_data['name']

                # 查询 type 表中的 src 和 price
                cursor.execute("SELECT pri_link, price, type FROM type WHERE typeID = %s", (type_id,))
                type_info = cursor.fetchone()

                if not type_info:
                    return jsonify({'status': 0, 'message': '商品可能已经下架4'}), 200

                pri_link = type_info['pri_link']
                price = type_info['price']
                order_type = type_info['type']

                # 新增订单记录
                order_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}{type_id}"
                date = datetime.now().date()
                postage = 10.0  # 邮费为 10.0

                total_price = price * num  # 计算总价

                cursor.execute(
                    "INSERT INTO orders (order_id, userid, src, date, type, shop, quantity, price, postage) "
                    "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                    (order_id, userID, pri_link, date, order_type, shop, num, total_price, postage)
                )
                connection.commit()

                return jsonify({'status': 1, 'message': '购买成功'}), 200

        except Exception as e:
            print(f"处理购买请求时出错: {e}")
            if 'connection' in locals():
                connection.rollback()
            return jsonify({'status': 0, 'message': '处理购买请求时出错'}), 500
        finally:
            if 'connection' in locals():
                connection.close()


def update_inventory(type_id, quantity_to_decrease):
    try:
        # 获取数据库连接
        connection = get_db_connection()
        with connection.cursor() as cursor:
            # 查询 type 表中的当前库存
            cursor.execute("SELECT quantity FROM type WHERE typeID = %s", (type_id,))
            type_data = cursor.fetchone()

            if not type_data:
                return 0  # 商品不存在

            current_quantity = type_data['quantity']

            # 检查库存是否足够
            if quantity_to_decrease > current_quantity:
                return 0  # 库存不足

            # 更新 type 表中的库存数量
            new_quantity = current_quantity - quantity_to_decrease
            cursor.execute("UPDATE type SET quantity = %s WHERE typeID = %s", (new_quantity, type_id))
            connection.commit()

            return 1  # 成功更新库存
    except Exception as e:
        print(f"更新库存时出错: {e}")
        if 'connection' in locals():
            connection.rollback()
        return 0
    finally:
        if 'connection' in locals():
            connection.close()


# 配置文件上传目录
app.config['COMMENT_FOLDER'] = r'C:\Users\21270\Desktop\qaq\src\static\comment'  # 图片保存路径


class File:
    def __init__(self, file):
        self.file = file

    def save(self, path):
        if self.file:
            filename = secure_filename(self.file.filename)
            self.file.save(os.path.join(path, filename))
            return os.path.join(path, filename)
        return None


class AddCommentAPI(MethodView):
    def post(self):
        try:
            # 获取前端传递的内容和文件列表
            content = request.form.get('content')
            productid = request.form.get('productid')
            num = int(request.form.get('num'))  # 图片数量
            userid = userID  # 假设这里已经定义了userID变量

            # 文件保存路径
            comment_folder = app.config['COMMENT_FOLDER']

            # 检查目录是否存在，不存在则创建
            if not os.path.exists(comment_folder):
                os.makedirs(comment_folder)

            links = []
            for i in range(1, num + 1):  # 循环到 num + 1
                file_key = f'file{i}'
                file = request.files.get(file_key)
                if file and file.filename != '':
                    file_obj = File(file)
                    filepath = file_obj.save(comment_folder)
                    if filepath:
                        relative_path = os.path.relpath(filepath, start='C:\\Users\\21270\\Desktop\\qaq')
                        relative_path = '/' + relative_path.replace('\\', '/')
                        links.append(relative_path)

            link_str = ",".join(links)  # 将文件路径转换为字符串形式

            current_time = datetime.now()

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 插入新评论记录
                sql = """
                    INSERT INTO comment (productid, userid, date, content, link)
                    VALUES (%s, %s, %s, %s, %s)
                """
                cursor.execute(sql, (productid, userid, current_time, content, link_str))
                connection.commit()

            return {'message': '评论成功'}, 200

        except Exception as e:
            print(f"处理评论时出错: {e}")
            if 'connection' in locals():
                connection.rollback()
            return {'message': '提交失败，请稍后再试'}, 500
        finally:
            if 'connection' in locals():
                connection.close()


class FetchCommentAPI(MethodView):
    def get(self):
        try:
            productid = request.args.get('Pro_id')

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 查询评论数据
                sql_comments = """
                    SELECT productid, userid, date, content, link
                    FROM comment
                    WHERE productid = %s
                """
                cursor.execute(sql_comments, (productid,))
                comments = cursor.fetchall()
                print(comments)  # 打印评论数据

                formatted_comments = []
                for comment in comments:
                    productid = comment['productid']
                    userid = comment['userid']
                    date = comment['date']
                    content = comment['content']
                    link = comment['link']

                    print(f"当前评论的 userid: {userid}")  # 打印 userid

                    # 查询用户数据
                    sql_user = """
                        SELECT username, head
                        FROM user
                        WHERE id = %s
                    """
                    cursor.execute(sql_user, (userid,))
                    user = cursor.fetchone()
                    print(f"查询用户数据：userid={userid}, 结果={user}")  # 打印用户数据查询结果

                    user_name = user['username']
                    user_head = user['head']
                    if user:
                        formatted_comment = {
                            'user_id': userid,
                            'user_name': user_name,
                            'user_img': user_head,
                            'words': content,
                            'time': date.strftime('%Y-%m-%d'),
                            'src': link.split(',') if link else []
                        }
                        formatted_comments.append(formatted_comment)

                return jsonify(formatted_comments), 200

        except Exception as e:
            print(f"获取评论时出错: {e}")
            return {'message': '获取评论失败，请稍后再试'}, 500
        finally:
            if 'connection' in locals():
                connection.close()


class AddProductAPI(MethodView):
    def post(self):
        try:
            # 获取前端传递的产品名称
            name = request.json.get('name')

            if not name:
                return {'message': '缺少产品名称'}, 400

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 插入新产品记录
                sql = """
                    INSERT INTO product (name,owner_id)
                    VALUES  (%s,%s)
                """
                cursor.execute(sql, (name, userID))
                connection.commit()

            with connection.cursor() as cursor:
                sql = """
                    SELECT productID from product WHERE name=%s AND owner_id=%s
                """
                cursor.execute(sql, (name, userID))
                connection.commit()
                addid = cursor.fetchone()
                global ADDID
                ADDID = addid['productID']
                print(ADDID)

            return {'message': '商品名称添加成功'}, 200


        except Exception as e:
            print(f"商品名称添加时出错: {e}")
            if 'connection' in locals():
                connection.rollback()
            return {'message': '商品名称添加失败，请稍后再试'}, 500
        finally:
            if 'connection' in locals():
                connection.close()


app.config['NEW_FOLDER'] = r'C:\Users\21270\Desktop\qaq\src\static\new'  # 图片保存路径


class AddCategoryAPI(MethodView):
    def post(self):
        try:
            # 获取前端传递的数据
            quantity = request.form.get('quantity')
            detail = request.form.get('detail')
            price = request.form.get('price')
            print(quantity, detail, price)
            if not quantity or not detail or not price:
                return {'message': '缺少商品名称、描述或价格'}, 400

            # 文件保存路径
            upload_folder = app.config['NEW_FOLDER']
            if not os.path.exists(upload_folder):
                os.makedirs(upload_folder)

            file_links = []
            for i in range(1, 5):  # 循环到 5
                file_key = f'file{i}'
                file = request.files.get(file_key)
                if file and file.filename != '':
                    filename = secure_filename(file.filename)
                    filepath = os.path.join(upload_folder, filename)
                    file.save(filepath)
                    relative_path = os.path.relpath(filepath, start=r'C:\Users\21270\Desktop\qaq')
                    relative_path = '/' + relative_path.replace('\\', '/')  # 转换为相对路径
                    file_links.append(relative_path)

            link_str = ",".join(file_links)  # 将文件路径转换为字符串形式

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 插入新产品记录
                sql_product = """
                    INSERT INTO type (quantity, type, price,productID,pri_link)
                    VALUES (%s, %s, %s,%s,%s)
                """
                cursor.execute(sql_product, (quantity, detail, price, ADDID, link_str))
                connection.commit()

            return {'message': '商品添加成功'}, 200

        except Exception as e:
            print(f"处理商品添加时出错: {e}")
            if 'connection' in locals():
                connection.rollback()
            return {'message': '商品添加失败，请稍后再试'}, 500
        finally:
            if 'connection' in locals():
                connection.close()

    def delete(self):
        ADDID = None
        print(ADDID)
        return {'message': '商品删除成功'}, 200


class DeleteProductAPI(MethodView):
    def delete(self):
        try:
            # 获取前端传递的产品 ID
            data = request.get_json()
            product_id = data.get('id')
            print(product_id)
            if product_id is None:
                return {'message': '缺少商品 ID'}, 400

            # 获取数据库连接
            connection = get_db_connection()
            with connection.cursor() as cursor:
                # 查询并删除产品记录
                sql = "DELETE FROM type WHERE typeID = %s"
                cursor.execute(sql, (product_id,))
                affected_rows = cursor.rowcount

            if affected_rows == 0:
                return {'message': '商品不存在'}, 404

            connection.commit()

            return {'message': '商品删除成功'}, 200

        except Exception as e:
            print(f"商品删除时出错: {e}")
            connection.rollback()
            return {'message': '商品删除失败，请稍后再试'}, 500
        finally:
            connection.close()


class ProductListView(MethodView):
    def get(self):
        try:
            # 获取请求参数
            store_id = request.args.get('store_id')

            if store_id is None:
                return {'message': '缺少 store_id 参数'}, 400

            # 获取数据库连接
            connection = get_db_connection()
            if connection is None:
                return {'message': '无法获取数据库连接'}, 500

            # 查询指定商家的所有 product_id
            with connection.cursor() as cursor:
                print(f"正在执行 SQL 查询: SELECT  FROM product WHERE owner_id = %s")
                cursor.execute("SELECT productID FROM product WHERE owner_id = %s", (store_id,))
                product_ids = cursor.fetchall()
                product_ids = [row['productID'] for row in product_ids]  # 提取 productID 的值
                print(f"查询结果: {product_ids}")

            # 根据 product_id 获取详细信息
            product_details = []
            for product_id in product_ids:
                with connection.cursor() as cursor:  # 每次查询时重新获取 cursor
                    print(f"正在执行 SQL 查询: SELECT pri_link, price, typeID, type FROM type WHERE productID = %s")
                    print(f"product_id: {product_id}")
                    cursor.execute("SELECT pri_link, price, typeID, type FROM type WHERE productID = %s", (product_id,))
                    type_info = cursor.fetchone()
                    print(f"type_info: {type_info}")
                    if type_info is None:
                        print(f"未找到 productID {product_id} 的 type 信息")
                        continue

                    with connection.cursor() as cursor:  # 再次获取新的 cursor
                        print(f"正在执行 SQL 查询: SELECT name FROM product WHERE productID = %s")
                        cursor.execute("SELECT name FROM product WHERE productID = %s", (product_id,))
                        product_name_row = cursor.fetchone()
                        print(f"product_name_row: {product_name_row}")
                        if product_name_row is None:
                            print(f"未找到 productID {product_id} 的名称")
                            continue
                        # 一直到这里都没问题
                        product_name = product_name_row['name']  # 使用字典形式提取 name
                        src_list = type_info['pri_link'].split(',')  # 分割 src 字段

                        for src in src_list:
                            product_details.append({
                                'src': src.strip(),  # 去除多余的空格
                                'name': product_name,
                                'price': float(type_info['price']),
                                'id': type_info['typeID'],
                                'detail': type_info['type']
                            })

            return jsonify(product_details), 200

        except Exception as e:
            print(f"处理商品查询时出错: {e}")
            return jsonify({'error': '处理商品查询时出错'}), 500



import sqlite3


class StoreProductView(MethodView):
    def post(self):
        try:
            # 获取请求数据
            data = request.json

            # 检查必填字段是否存在
            required_fields = ['type_id', 'name', 'price', 'detail']
            missing_fields = [field for field in required_fields if field not in data]

            if missing_fields:
                return jsonify({'error': f'缺少必填字段: {", ".join(missing_fields)}'}), 400

            # 获取数据库连接
            connection = get_db_connection()
            if connection is None:
                return jsonify({'message': '无法获取数据库连接'}), 500

            # 更新 type 表
            with connection:
                cursor = connection.cursor()
                cursor.execute(
                    "UPDATE type SET price = %s, type = %s WHERE typeID = %s",
                    (data['price'], data['detail'], data['type_id'])

                )
                print(data['type_id'])
                if cursor.rowcount == 0:
                    return jsonify({'error': '没有找到匹配的记录'}), 404

                # 获取对应的 product_id
                cursor.execute(
                    "SELECT productID FROM type WHERE typeID = %s",
                    (data['type_id'],)
                )
                product_id_row = cursor.fetchone()
                if product_id_row is None:
                    return jsonify({'error': '未找到对应的 product_id'}), 404

                product_id = product_id_row['productID']

                # 更新 product 表
                cursor.execute(
                    "UPDATE product SET name = %s WHERE productID = %s",
                    (data['name'], product_id)
                )

                if cursor.rowcount == 0:
                    return jsonify({'error': '没有找到匹配的 product 记录'}), 404

                connection.commit()

            return jsonify({'message': '修改成功'}), 200

        except Exception as e:
            print(f"处理商品更新时出错: {e}")
            return jsonify({'error': '处理商品更新时出错'}), 500


# 注册路由
store_product_view = StoreProductView.as_view('store_product_view')
app.add_url_rule('/store', view_func=store_product_view, methods=['POST'])

# 注册路由
product_list_view = ProductListView.as_view('product_list_view')
app.add_url_rule('/product', view_func=product_list_view, methods=['GET'])

# 注册路由
delete_product_view = DeleteProductAPI.as_view('delete_product_api')
app.add_url_rule('/store', view_func=delete_product_view, methods=['DELETE'])

# 注册路由
add_category_view = AddCategoryAPI.as_view('add_category_api')
app.add_url_rule('/store/addcategory', view_func=add_category_view, methods=['POST', 'DELETE'])

# 注册路由
add_product_view = AddProductAPI.as_view('add_product_api')
app.add_url_rule('/store/addproduct', view_func=add_product_view, methods=['POST'])

# 评论
fetch_comment_view = FetchCommentAPI.as_view('fetch_comment_api')
app.add_url_rule('/comment', view_func=fetch_comment_view, methods=['GET'])

# 评论
add_comment_view = AddCommentAPI.as_view('add_comment_api')
app.add_url_rule('/comment', view_func=add_comment_view, methods=['POST'])

# 添加购买接口
add_order_view = AddOrderView.as_view('add_order_view')
app.add_url_rule('/order/add', view_func=add_order_view, methods=['POST'])

# 添加购买接口
buy_view = BuyView.as_view('buy_view')
app.add_url_rule('/buy', view_func=buy_view, methods=['POST'])

# 添加获取商品列表接口
products_view = ProductsView.as_view('products_view')
app.add_url_rule('/store', view_func=products_view, methods=['POST'])

# 添加获取商店接口
stores_view = StoresView.as_view('stores_view')
app.add_url_rule('/store', view_func=stores_view, methods=['GET'])

# 添加获取订单接口
orders_view = OrdersView.as_view('orders_view')
app.add_url_rule('/order', view_func=orders_view, methods=['GET'])

# 添加创建店铺接口
shop_view = ShopView.as_view('shop_view')
app.add_url_rule('/shop', view_func=shop_view, methods=['POST'])

# 添加上传头像接口
upload_avatar_view = UploadAvatarView.as_view('upload_avatar_view')
app.add_url_rule('/user', view_func=upload_avatar_view, methods=['PUT'])

# 添加获取用户信息接口
get_user_view = GetUserView.as_view('get_user_view')
app.add_url_rule('/user', view_func=get_user_view, methods=['GET'])

# 添加更新用户信息接口
update_user_view = UpdateUserView.as_view('update_user_view')
app.add_url_rule('/user', view_func=update_user_view, methods=['POST'])

# 添加登出接口
logout_view = LogoutView.as_view('logout_view')
app.add_url_rule('/logout', view_func=logout_view, methods=['POST'])

# 添加删除购物车商品接口
delete_cart_items_view = DeleteCartItemsView.as_view('delete_cart_items_view')
app.add_url_rule('/cart', view_func=delete_cart_items_view, methods=['DELETE'])

# 添加获取购物车列表接口
get_cart_list_view = GetCartView.as_view('get_cart_list_view')
app.add_url_rule('/cart', view_func=get_cart_list_view, methods=['GET'])

# 添加获取产品列表接口
get_pro_list_view = GetProListView.as_view('get_pro_list_view')
app.add_url_rule('/getProList', view_func=get_pro_list_view, methods=['GET'])

# 添加产品详情接口
product_detail_view = ProductDetailAPI.as_view('product_detail_api')
app.add_url_rule('/product/detail', view_func=product_detail_view, methods=['GET'])

# 添加产品详情接口2
product_details_view = ProductDetailsAPI.as_view('product_details_api')
app.add_url_rule('/products', view_func=product_details_view, methods=['GET'])

# 添加购物车接口
add_cart_view = AddCartAPI.as_view('add_cart_api')
app.add_url_rule('/addCart', view_func=add_cart_view, methods=['POST'])

# 添加购物车接口2
add_to_cart_view = AddToCartAPI.as_view('add_to_cart_api')
app.add_url_rule('/cart/add', view_func=add_to_cart_view, methods=['POST'])

# 登录
login_view = LoginAPI.as_view('login_api')
app.add_url_rule('/login', view_func=login_view, methods=['POST'])

# 注册
register_view = RegisterAPI.as_view('register_api')
app.add_url_rule('/register', view_func=register_view, methods=['POST'])



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)